package com.wnhz.work.yz.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.SellAfterApplyBean;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.UriUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SkillBookPop;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SellAfterApplyActivity extends BaseActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_after_apply);
        initTitle();
        initData();
        initView();
    }

    private TextView title;

    private void initTitle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("申请售后");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
    }

    private SellAfterApplyBean.InfoEntity.DataEntity data = new SellAfterApplyBean.InfoEntity.DataEntity();

    private String order_id;

    private void initData() {
        data = (SellAfterApplyBean.InfoEntity.DataEntity) getIntent().getSerializableExtra("data");
        order_id = getIntent().getStringExtra("order_id");
    }

    private ImageView iv_goods;
    private TextView tv_good_name, tv_goods_num;
    private Button add, delete, nums, tuihuo, submit2;
    private RadioGroup faPiao, checkBaoGao;
    private RadioButton faPiaoLi, faPiaoNor, checkLi, checkNor;
    private boolean checkBaoFlag = true, faPiaoFlag = true, isCheck1 = false, isCheck2 = false;
    private EditText edit;
    private ImageView add1;


    private void initView() {
        add1 = (ImageView) findViewById(R.id.add1);
        add1.setOnClickListener(this);
        ll_lost_selectpic = (LinearLayout) findViewById(R.id.ll_lost_selectpic);

        iv_goods = (ImageView) findViewById(R.id.iv_goods);
        tv_good_name = (TextView) findViewById(R.id.tv_good_name);
        tv_goods_num = (TextView) findViewById(R.id.tv_goods_num);
        edit = (EditText) findViewById(R.id.edit);
        add = (Button) findViewById(R.id.add);
        delete = (Button) findViewById(R.id.delete);
        nums = (Button) findViewById(R.id.nums);
        nums.setText("1");
        tuihuo = (Button) findViewById(R.id.tuihuo);
        tuihuo.setTextColor(getResources().getColor(R.color.red));
        tuihuo.setBackgroundResource(R.drawable.btn_blue2);
        tuihuo.setOnClickListener(this);
        delete.setOnClickListener(this);
        add.setOnClickListener(this);
        submit2 = (Button) findViewById(R.id.submit2);
        submit2.setOnClickListener(this);
        faPiao = (RadioGroup) findViewById(R.id.faPiao);
        checkBaoGao = (RadioGroup) findViewById(R.id.checkBaoGao);
        faPiao.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                isCheck1 = true;
                if (checkedId == faPiaoLi.getId()) {
                    faPiaoFlag = true;
                } else {
                    faPiaoFlag = false;
                }
            }
        });
        checkBaoGao.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                isCheck2 = true;
                if (checkedId == checkLi.getId()) {
                    checkBaoFlag = true;
                } else {
                    checkBaoFlag = false;
                }
            }
        });

        faPiaoLi = (RadioButton) findViewById(R.id.faPiaoLi);
        faPiaoNor = (RadioButton) findViewById(R.id.faPiaoNor);
        checkLi = (RadioButton) findViewById(R.id.checkLi);
        checkNor = (RadioButton) findViewById(R.id.checkNor);
        checkBaoGao = (RadioGroup) findViewById(R.id.checkBaoGao);
        checkBaoGao = (RadioGroup) findViewById(R.id.checkBaoGao);


        x.image().bind(iv_goods, data.getGoods_spic());
        tv_good_name.setText(data.getGoods_name());
        tv_goods_num.setText("数量*" + data.getGoods_nums());

    }

    private boolean isTuiHuo = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.add:
                if (Integer.parseInt(nums.getText().toString().equals("") ? Integer.parseInt(data.getGoods_nums()) - 1 + "" : nums.getText().toString()) < Integer.parseInt(data.getGoods_nums())) {
                    nums.setText(Integer.parseInt(nums.getText().toString()) + 1 + "");
                } else {
                    Toast.makeText(SellAfterApplyActivity.this, "不能再加了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.delete:
                if (Integer.parseInt(nums.getText().toString()) > 1) {
                    nums.setText(Integer.parseInt(nums.getText().toString().equals("") ? "1" : nums.getText().toString()) - 1 + "");
                } else {
                    Toast.makeText(SellAfterApplyActivity.this, "不能再减了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tuihuo:
//                Toast.makeText(SellAfterApplyActivity.this, ""+isTuiHuo, Toast.LENGTH_SHORT).show();
                isTuiHuo = !isTuiHuo;
                if (isTuiHuo) {
                    tuihuo.setTextColor(getResources().getColor(R.color.red));
                    tuihuo.setBackgroundResource(R.drawable.btn_blue2);
                } else {
                    tuihuo.setBackgroundResource(R.drawable.btn_white);
                    tuihuo.setTextColor(getResources().getColor(R.color.text));
                }
                break;
            case R.id.submit2:
                if (!isTuiHuo) {
                    Toast.makeText(SellAfterApplyActivity.this, "请选择服务类型", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if ("".equals(edit.getText())){
//                    Toast.makeText(SellAfterApplyActivity.this, "售后信息不能为空", Toast.LENGTH_SHORT).show();
//                }
                if (!isCheck1) {
                    Toast.makeText(SellAfterApplyActivity.this, "请选择发票", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isCheck2) {
                    Toast.makeText(SellAfterApplyActivity.this, "请选择检查报告", Toast.LENGTH_SHORT).show();
                    return;
                }

                showDialogv7("确认提交售后吗？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showDialog();
                        upLoad();
                    }
                });

                break;
            //
            case R.id.add1:
//                Intent intent = new Intent(SellAfterApplyActivity.this, SelectImageActivity.class);
//                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                showPopmenu(v);
                break;
        }
    }

    private SkillBookPop menuWindow;
    private WindowManager.LayoutParams lp;

    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private String imageName;// 原图名称
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    System.out.println("=====1234=====");
                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    System.out.println("拍照的路径---" + imageName);
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:

//                    intent = new Intent(Intent.ACTION_GET_CONTENT);
//                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                    startActivityForResult(intent, FROM_ALBUM_CODE);
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);
                    break;

                default:
                    break;
            }
        }
    };


    private LinearLayout ll_lost_selectpic;
    /*图片文件路径*/
    private List<String> pathList = new ArrayList<String>();
    /*请求标识*/
    private static final int REQUEST_CODE_PICK_IMAGE = 1;
    public static final int CAMERA1 = 123, CAMERA2 = 456;
    String str[] = new String[5];
    private File tempFile;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:

                if (data != null) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String imagePath2 = c.getString(columnIndex);
                    updateImage(imagePath2, selectedImage, true);
                    c.close();
                }
                //有了照片路径，之后就是压缩图片，和之前没有什么区别
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {

                    tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    System.out.println("拍照的路径=====：" + imagePath);

//                    if (!compressFile.exists()) {
//                        compressFile = new File(FilesPath);
//                        compressFile.mkdirs();
//                    }
                    File file = new File(imagePath);
//                    Log.i(TAG, "onActivityResult: 拍照图片是否存在===" + file.exists());

                    if (!file.exists()) {
                        return;
                    }

//                    String targetPath = compressFile.getAbsolutePath() + df.format(new Date()) + ".jpg";
//                    //调用压缩图片的方法，返回压缩后的图片path
//                    final String compressImage = CompressImageUtils.compressImage(imagePath, targetPath, 60);
//                    Log.i(TAG, "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
//
//                    updateImage(compressImage, uri, currentClick);
                    updateImage(imagePath, uri, false);

                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;


            default:
                break;
        }

    }

    private ActionBar.LayoutParams params;

    ImageOptions options = new ImageOptions.Builder()
            //设置加载过程中的图片
            .setLoadingDrawableId(R.mipmap.ic_morentouxiang)
            //设置加载失败后的图片
            .setFailureDrawableId(R.mipmap.ic_morentouxiang)
            //设置使用缓存
            .setUseMemCache(true)
            //设置显示圆形图片
            .setCircular(false)
            //设置支持gif
            .setIgnoreGif(false)
            .build();

    private void updateImage(String imagePath, Uri uri, boolean flag) {
        if (null == imagePath) {
            return;
        }

        System.out.println("===修改的imagePath===" + imagePath);
//        ImageLoader.getInstance().displayImage("file://" + imagePath, iv_edit_head);
//        x.image().bind(iv_edit_head, "file://" + imagePath, options);
        //新建一个ImageView
        final ImageView imageView = new ImageView(SellAfterApplyActivity.this);
        int winths = getWindow().getWindowManager().getDefaultDisplay().getWidth() / 7 - 10;
        params = new ActionBar.LayoutParams(winths, winths);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        //  params.setMargins(50,50,50,50);
        ImageLoader.getInstance().displayImage("file://" + imagePath, imageView);
        x.image().bind(imageView, "file://" + imagePath, options);
//                Picasso.with(SellAfterApplyActivity.this)
//                        .load(uri)
//                        .placeholder(R.drawable.loading)
//                        .error(R.mipmap.ic_tianjiatupian)
//                        .into(imageView);
//                imageURIList.add(imageId);
        imageView.setLayoutParams(params);
//                pathList.add(uri.toString());
        final ImageView cha = new ImageView(SellAfterApplyActivity.this);
        params = new ActionBar.LayoutParams(50, 50);
        cha.setLayoutParams(params);
        cha.setImageResource(R.drawable.forum_tag_close);
        pathList.add(UriUtil.getImageAbsolutePath(SellAfterApplyActivity.this, uri));
        ll_lost_selectpic.addView(imageView);
        ll_lost_selectpic.addView(cha);
        int index = ll_lost_selectpic.getChildCount() / 2 - 1;
        if (flag) {
            str[index] = imagePath;
        } else
            str[index] = uri.toString();
        cha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_lost_selectpic.removeView(imageView);
                ll_lost_selectpic.removeView(cha);
            }
        });
        //   WindowsTools.removePic(ll_lost_selectpic, imageView, MainActivity.this);
        for (int i = 0; i < 5; i++) {
            Log.e("---", str[i] + "");
        }
    }

//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        Uri uri = null;
//
//        ActionBar.LayoutParams params = null;
//        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
//            if (data == null) {
//                return;
//            }
//            try {
//                uri = Uri.parse(data.getStringExtra("uri"));
//
//                //新建一个ImageView
//                final ImageView imageView = new ImageView(SellAfterApplyActivity.this);
//                int winths = getWindow().getWindowManager().getDefaultDisplay().getWidth() / 7 - 10;
//                params = new ActionBar.LayoutParams(winths, winths);
//                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//                //  params.setMargins(50,50,50,50);
//
//                x.image().bind(imageView, uri.toString());
////                Picasso.with(SellAfterApplyActivity.this)
////                        .load(uri)
////                        .placeholder(R.drawable.loading)
////                        .error(R.mipmap.ic_tianjiatupian)
////                        .into(imageView);
////                imageURIList.add(imageId);
//                imageView.setLayoutParams(params);
////                pathList.add(uri.toString());
//                final ImageView cha = new ImageView(SellAfterApplyActivity.this);
//                params = new ActionBar.LayoutParams(50, 50);
//                cha.setLayoutParams(params);
//                cha.setImageResource(R.drawable.forum_tag_close);
//                pathList.add(UriUtil.getImageAbsolutePath(SellAfterApplyActivity.this, uri));
//                ll_lost_selectpic.addView(imageView);
//                ll_lost_selectpic.addView(cha);
//                int index = ll_lost_selectpic.getChildCount() / 2 - 1;
//                str[index] = uri.toString();
//                cha.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        ll_lost_selectpic.removeView(imageView);
//                        ll_lost_selectpic.removeView(cha);
//                    }
//                });
//                //   WindowsTools.removePic(ll_lost_selectpic, imageView, MainActivity.this);
//                for (int i = 0; i < 5; i++) {
//                    Log.e("---", str[i] + "aaa");
//                }
//            } catch (Exception e) {
//            }
//        }
//    }


    /**
     * 提交售后申请 Order_afterSalesService
     * orderid goodsid servicetype  nums ischeck message  type  token pic%d
     */
    private String info;

    private void upLoad() {
        Map<String, Object> map = new Hashtable<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", order_id);
        map.put("goodsid", data.getGoods_id());
        map.put("servicetype", "1");
        map.put("nums", nums.getText());
        map.put("ischeck", checkBaoFlag ? "1" : "0");
        map.put("message", edit.getText());
        map.put("type", faPiaoFlag ? "1" : "0");
        for (int i = 0; i < 5; i++) {
            if (str[i] != null) {
                String targetPath = str[i];
                //调用压缩图片的方法，返回压缩后的图片path
                String compressImage = BitnapUtils.compressImage(targetPath, targetPath, 30);
                File compressedPic = new File(compressImage);
                map.put("pic" + (i + 1), compressedPic);
            }
        }

        StringBuffer a = new StringBuffer("");
        Set set = map.entrySet();
        if (set != null) {
            Iterator it = set.iterator();
            while (it.hasNext()) {
                Map.Entry en = (Map.Entry) it.next();
                a.append("" + en.getKey() + "---" + en.getValue() + "\n");
            }
        }
        Log.e("----", a.toString());

        XUtil.Post(Url.ORDER_AFTERSALESSERVICE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                Log.e("------", result);
                closeDialog();
                try {
                    JSONObject res = new JSONObject(result);
                    info = res.optString("info");
                    if ("1".equals(res.optString("result"))) {
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
                Toast.makeText(SellAfterApplyActivity.this, info, Toast.LENGTH_SHORT).show();
            }
        });
    }


}
